<template>
    <div class="login-view h-full w-full" flex flex-justify-center flex-items-center>
        <n-card title="登录" hoverable class="login-view-container">
            <n-form ref="formRef" :model="modelRef" :rules="rules" label-placement="left" :theme-overrides="theme">
                <n-form-item path="username">
                    <n-input v-model:value="modelRef.username" placeholder="请输入员工编号" round clearable>
                        <template #prefix>
                            <n-icon :component="PersonOutline" />
                        </template>
                    </n-input>
                </n-form-item>
                <n-form-item path="password">
                    <n-input
                        v-model:value="modelRef.password"
                        type="password"
                        placeholder="请输入密码"
                        round
                        clearable
                        show-password-on="click"
                    >
                        <template #prefix>
                            <n-icon :component="KeySharp" />
                        </template>
                    </n-input>
                </n-form-item>
                <n-form-item>
                    <n-button type="primary" attr-type="submit" @click="handleLogin" :loading="loading" block round> 登录 </n-button>
                </n-form-item>
            </n-form>
        </n-card>
    </div>
</template>

<script setup lang="ts">
import { FormInst, FormProps, FormRules } from "naive-ui"
import { PersonOutline, KeySharp } from "@vicons/ionicons5"
import { doLogin } from "@/hooks/authorization"

interface LoginModel {
    username: string
    password: string
}

const formRef = ref<FormInst | null>(null)
const modelRef = ref<LoginModel>({
    username: "",
    password: ""
})

const rules: FormRules = {
    username: [{ required: true, message: "请输入员工编号" }],
    password: [{ required: true, message: "请输入密码" }]
}

const theme: NonNullable<FormProps["themeOverrides"]> = {
    feedbackFontSizeMedium: "10px"
}

const loading = ref<boolean>(false)
const handleLogin = (e: MouseEvent) => {
    e.preventDefault()
    loading.value = true
    formRef.value
        ?.validate(async errors => {
            if (!errors) {
                const { username, password } = modelRef.value
                await doLogin(username, password)
                loading.value = false
            }
        })
        .catch(() => (loading.value = false))
}
</script>

<style lang="less" scoped>
.login-view {
    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url(/src/assets/login-bg.jpeg);
        background-repeat: no-repeat;
        background-position: 100%;
        background-size: 100% 100%;
    }

    &-container {
        width: 500px;
        border-radius: 10px;
    }
}
</style>
